<template>
	<!-- 使用 page-meta 组件配合阻止滚动穿透 ,page-meta一定作为页面的第一个节点-->
	<page-meta :page-style="'overflow:'+(show?'hidden':'visible')"></page-meta>

	<uni-popup ref="loginPopup" type="bottom" @change="changePop" :isMaskClick="false" :safeArea="false">
		<my-login-pop :loginConfirm="loginConfirm" @close="loginPopClose"></my-login-pop>
	</uni-popup>

	<uni-popup ref="addPopup" type="bottom" @change="changePop" :safeArea="false">
		<my-add-fridge-pop @close="addPopClose"></my-add-fridge-pop>
	</uni-popup>
	<uni-popup ref="msgPopup" type="center" @change="changePop">
		<my-msg-pop :msg="latest_msg" @delete="deleteMsg" @close="closeMsgPop"></my-msg-pop>
	</uni-popup>

	<view class="home-container">

		<uni-notice-bar show-get-more show-icon scrollable color="#2979FF" moreColor="#2979FF"
			background-color="#EAF2FF" :text="latest_msg.content" @click="readMsg"
			v-if="latest_msg.msgId&&!latest_msg.handlerId" />

		<uni-swiper-dot class="uni-swiper-dot-box" @clickItem=clickItem :info="info" :current="current" :mode="'dot'"
			:dotsStyles="dotStyle">
			<swiper class="swiper-box" @change="change" :current="swiperDotIndex" :circular="true" :autoplay="true"
				:interval="5000">
				<swiper-item v-for="(item, index) in 3" :key="index">
					<view class="swiper-item">
						<image :src="info[index].imgUrl" style="width: 100%;height: 100%;" mode="scaleToFill">
						</image>
					</view>
				</swiper-item>
			</swiper>
		</uni-swiper-dot>

		<view class="main-view op-view">
			<view class="title-row">
				<view class="box">
					<text>物资管理</text>
					<view class="fridge-msg" @tap.stop="gotoFridgeInner">
						<iconfont :name="'fridge'" :size="16" :color="'#b7bdc5'"></iconfont>
						<text>{{default_fridge.name||''}}</text>
					</view>
				</view>
			</view>
			<view class="content-row">
				<view class="item-view" hover-class="hover-item-view" v-for="(item,i) in tips_list" :key="i"
					@click="opClickHandler(i)">
					<uni-badge class="uni-badge-left-margin" :text="item.num" :maxNum="99" absolute="rightTop"
						:offset="[0, 0]" size="normal" :customStyle="{background: item.color}">
						<iconfont :name="item.img" :size="40" :color="item.color"></iconfont>
					</uni-badge>
					<text :style="{color:item.color}">{{item.text}}</text>
				</view>
			</view>
		</view>

		<view class="main-view menu-view">

			<!-- 			<view class="title-row">
				<view class="box">
					<text>菜谱推荐</text>
				</view>
			</view>
 -->
			<scroll-view scroll-y="true" style="height: 100%; width: 100%;" type="custom"
				v-if="_recommand_menu_list.length!=0">
				<grid-view type="masonry" cross-axis-count="2" cross-axis-gap="10" main-axis-gap="18">
					<view :class="['grid-box',{'first-row':i<=1}]" v-for="(item,i) in _recommand_menu_list"
						:key="item.id" @click="gotoMenuDetail(item.id)">
						<image style="border-radius: 20rpx 20rpx 0 0; width: 100%;" :src="item.imgSrc" lazy-load="true"
							mode="widthFix">
						</image>
						<view class="msg-text"><text>{{item.name}}</text></view>
					</view>
				</grid-view>
				<view class="load-more" style="padding-bottom: 15px;">
					<uni-load-more color="#007AFF" :status="status" :content-text="contentText" />
				</view>
			</scroll-view>
		</view>
		<view class="scroll-btn" v-if="floorStatus" @click="scollToTop">
			<iconfont :name="'scroll_top'" :size="80" :color="'rgb(194, 199, 206,0.3)'"></iconfont>
		</view>
	</view>
</template>

<script>
	// 导入自己封装的 mixin 模块
	import badgeMix from '@/mixins/tabbar-badge.js'

	import {
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex'

	export default {
		data() {
			return {
				show: false,
				loginConfirm: false,
				// 别人邀请你加入冰箱的fid
				fid: '',
				tips_list: [{
					text: '过期',
					color: '#fc501c',
					img: 'danger',
					num: 0
				}, {
					text: '临期',
					color: '#f98700',
					img: 'warn',
					num: 0
				}, {
					text: '购物清单',
					color: '#2979FF',
					img: 'cart',
					num: 0
				}],

				// 轮播图
				info: [{
					imgUrl: 'https://img.zcool.cn/community/0133fe5a02de22a801216a4b558563.png@1280w_1l_2o_100sh.png'
				}, {
					imgUrl: 'https://img.zcool.cn/community/0108e55c8cae00a801214168a20753.jpg@1280w_1l_2o_100sh.jpg'
				}, {
					imgUrl: 'https://ts1.cn.mm.bing.net/th/id/R-C.7823b7ffa2abf13b3b7666120436ac71?rik=ZSctCHnoaxNn0w&riu=http%3a%2f%2fimg.aiimg.com%2fuploads%2fuserup%2f1105%2f0913112S3D.jpg&ehk=4Cvmovm%2fe2HCwXWsIsqOMQ7VLqeQ%2fey9DQTAEVHnRnA%3d&risl=&pid=ImgRaw&r=0'
				}],
				current: 0,
				swiperDotIndex: 0,
				dotStyle: {
					backgroundColor: 'rgba(83, 200, 249,0.3)',
					border: '1px rgba(83, 200, 249,0.3) solid',
					color: '#fff',
					selectedBackgroundColor: 'rgba(83, 200, 249,0.9)',
					selectedBorder: '1px rgba(83, 200, 249,0.9) solid'
				},
				// 推荐菜谱
				recommand_menu_list: [],
				// 是否显示返回顶部的按键
				floorStatus: false,
				// 显示的条数
				num: 6,
				status: 'more',
				contentText: {
					contentdown: '查看更多',
					contentrefresh: '加载中...',
					contentnomore: '没有更多了'
				}
			};
		},

		// 将 badgeMix 混入到当前的页面中进行使用
		mixins: [badgeMix],

		computed: {
			...mapState('user', ['token']),
			...mapState('fridge', ['default_fridge']),
			...mapState('object', ['obj_list']),
			...mapState('message', ['latest_msg']),
			...mapGetters('cart', ['total']),

			_recommand_menu_list() {
				// 分页加载
				return this.recommand_menu_list.slice(0, this.num)
			}
		},

		watch: {
			obj_list: {
				handler(newVal, oldVal) {
					let danger_num = 0
					let warn_num = 0
					this.obj_list.forEach(x => {
						if (x.shortestWarrantyTime <= 0) {
							danger_num = danger_num + 1
						} else if (x.shortestWarrantyTime < 7 && x.shortestWarrantyTime > 0) {
							warn_num = warn_num + 1
						}
					})
					this.tips_list[0].num = danger_num
					this.tips_list[1].num = warn_num
				},
				deep: true,
				immediate: true
			},
			token: {
				handler(newVal, oldVal) {
					if (newVal == '') {
						this.updateFridgeList([])
						this.updateObjList([])
						this.updateLatestMessage(null)
						uni.hideTabBar()
						this.$refs.loginPopup.open()
					}
				}
			}
		},

		onShow() {
			uni.setStorageSync('tabIndex', '')
			uni.setStorageSync('mode', '')
			uni.setStorageSync('modeIndex', '')
			this.tips_list[2].num = this.total
		},

		onLoad(options) {
			wx.showShareMenu({
				// withShareTicket: true,
				menus: ['shareAppMessage']
			})
			let scene = decodeURIComponent(options.scene);
			//&是我们定义的参数链接方式
			let fid = scene.split('=')[1];
			this.fid = options.fid || fid
			this.load()
		},

		onPullDownRefresh() {
			this.load()
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1000)
		},

		onPageScroll(e) {
			// console.log(e.scrollTop);
			if (e.scrollTop > 100)
				this.floorStatus = true
			else this.floorStatus = false
		},

		onReachBottom() {
			this.loadMore()
		},

		methods: {

			...mapMutations('fridge', ['updateFridgeList']),
			...mapMutations('object', ['updateObjList']),
			...mapMutations('message', ['updateLatestMessage']),

			load() {
				this.getRecommandMenuList()
				uni.showLoading({
					mask: true
				})
				if (this.token) {
					if (this.fid) {
						uni.$api.fridge.join(this.fid)
					} else
						uni.$api.fridge.getAll()
				} else {
					uni.hideTabBar()
					this.$refs.loginPopup.open()
				}
				setTimeout(() => {
					uni.hideLoading()
				}, 1000)
			},

			// 跳转
			opClickHandler(index) {
				if (!this.default_fridge.fid)
					return this.beforeJump()
				// 购物清单
				if (index == 2) {
					return uni.navigateTo({
						url: '/pagesSub/pageMenu/cart/cart'
					})
				}
				// 过期或临期
				uni.switchTab({
					url: '/pages/take_store/take_store'
				})
				uni.setStorageSync('mode', "time")
				uni.setStorageSync('modeIndex', index)
			},

			gotoFridgeInner() {
				if (!this.default_fridge.fid)
					return this.beforeJump()
				uni.navigateTo({
					url: '/pagesSub/pageFridge/fridge_detail/fridge_detail?fridge=' + JSON.stringify(this
						.default_fridge)
				})
			},

			gotoMenuDetail(menuId) {
				uni.navigateTo({
					url: '/pagesSub/pageMenu/menu_detail/menu_detail?menuId=' + menuId
				})
			},

			// 请求
			read() {
				if (!this.latest_msg.read)
					uni.$api.message.setRead([this.latest_msg.msgId])
			},
			deleteMsg() {
				uni.$api.message.deleteRead([this.latest_msg.msgId])
			},

			/**
			 * 获取推荐菜谱 v6
			 */
			async getRecommandMenuList() {
				await uni.$api.menu.getRecommendedMenu().then((list) => {
					this.recommand_menu_list = list
				})
			},

			// 事件处理
			beforeJump() {
				uni.showModal({
					title: 'Tips',
					content: '您尚未绑定冰箱，请先绑定冰箱',
					success: (res) => {
						if (res.confirm) {
							this.$refs.addPopup.open()
						}
					}
				})
			},
			changePop(e) {
				this.show = e.show
			},

			// 登录处理
			loginPopClose() {
				uni.getUserProfile({
					desc: '你的授权信息',
					success: async (res) => {
						console.log(res);
						this.loginConfirm = true
						await uni.$api.user.login(res.userInfo, this.fid).then((res) => {
							uni.$showMsg(res)
							this.$refs.loginPopup.close()
							uni.showTabBar()
						}).catch((reason) => {
							uni.$showMsg(reason)
						}).finally(() => {
							this.loginConfirm = false
						})
					},
					fail(res) {
						console.log(res);
						uni.$showMsg('您取消了登录授权')
					}
				})
			},
			addPopClose() {
				this.$refs.addPopup.close()
			},
			// 轮播图切换
			change(e) {
				this.current = e.detail.current
			},
			clickItem(e) {
				this.swiperDotIndex = e
			},
			readMsg() {
				this.read()
				this.$refs.msgPopup.open()
			},
			closeMsgPop() {
				this.$refs.msgPopup.close()
			},
			// 回到顶部
			scollToTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				})
			},
			// 加载更多
			loadMore() {
				if (this.status == 'more') {
					this.status = 'loading'
					setTimeout(() => {
						this.num = this.num + 6
						if (this.num < this.recommand_menu_list.length)
							this.status = 'more'
						else this.status = 'noMore'
					}, 1000)
				}
			}
		}
	}
</script>

<style lang="scss">
	.home-container {

		.uni-noticebar {
			padding: 5px 10px !important;
		}

		.swiper-box {
			height: 160px;
			padding: 0 25rpx 25rpx 25rpx;

			.swiper-item {
				/* #ifndef APP-NVUE */
				display: flex;
				/* #endif */
				flex-direction: column;
				justify-content: center;
				align-items: center;
				height: 100%;
				color: #fff;
				border-radius: 20rpx;
				background-color: #cee1fd;
				overflow: hidden;
			}
		}

		.main-view {
			background-color: #fff;
			border-radius: 20rpx;
			font-size: 16px;
			margin: 0 25rpx 25rpx 25rpx;

			.title-row {
				padding: 0 25rpx;
				font-size: 20px;
				background-color: #fff;
				border-radius: 20rpx 20rpx 0 0;

				.box {
					display: flex;
					flex: 1;
					padding: 25rpx 0;
					align-items: center;
					justify-content: space-between;
					border-bottom: 1rpx solid #e5e6eb;

					>text {}

					.fridge-msg {
						display: flex;
						align-items: center;

						>text {
							font-size: 14px;
							color: #b7bdc5;
						}
					}
				}
			}
		}

		.op-view {
			.content-row {
				display: flex;
				justify-content: center;
				padding: 20rpx 0;

				.item-view {
					display: flex;
					width: 30%;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					border-left: 1px solid #e5e6eb;
					border-right: 1px solid #e5e6eb;

					>text {
						margin-top: 10rpx;
					}
				}
			}
		}

		.hover-item-view {
			background-color: #f1f1f1;
		}

		.menu-view {
			background-color: #efefef;

			.grid-box {
				background-color: #fff;
				border-radius: 20rpx;

				.msg-text {
					font-size: 17px;
					text-align: center;
					padding: 0 5px;
					padding-bottom: 5px;
				}
			}

			.first-row {
				// background-color: #fff;
				// border-radius: 0 0 20rpx 20rpx;
			}
		}

		.scroll-btn {
			position: fixed;
			bottom: 50rpx;
			right: 30rpx;
		}

	}
</style>